#!/bin/bash

# MySQL MCP Server Docker 构建和运行脚本

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo "MySQL MCP Server Docker 管理脚本"
    echo ""
    echo "用法: $0 [命令] [选项]"
    echo ""
    echo "命令:"
    echo "  build     构建Docker镜像"
    echo "  up        启动服务"
    echo "  down      停止服务"
    echo "  restart   重启服务"
    echo "  logs      查看日志"
    echo "  clean     清理Docker资源"
    echo "  test      测试MCP服务器连接"
    echo "  help      显示帮助信息"
    echo ""
    echo "选项:"
    echo "  -d, --detach    后台运行"
    echo "  -f, --force     强制重新构建"
    echo "  --dev           使用开发环境配置"
    echo "  --prod          使用生产环境配置"
    echo ""
    echo "示例:"
    echo "  $0 build --force"
    echo "  $0 up --detach"
    echo "  $0 logs mysql-mcp-server"
}

# 检查Docker是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        print_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        print_error "Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi
    
    print_success "Docker 环境检查通过"
}

# 构建Docker镜像
build_image() {
    local force_rebuild=false
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            -f|--force)
                force_rebuild=true
                shift
                ;;
            *)
                shift
                ;;
        esac
    done
    
    print_info "开始构建 MySQL MCP Server Docker 镜像..."
    
    if [ "$force_rebuild" = true ]; then
        print_info "强制重新构建镜像..."
        docker-compose build --no-cache mysql-mcp-server
    else
        docker-compose build mysql-mcp-server
    fi
    
    print_success "Docker 镜像构建完成"
}

# 启动服务
start_services() {
    local detach=false
    local env_file="docker-compose.yml"
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            -d|--detach)
                detach=true
                shift
                ;;
            --dev)
                env_file="docker-compose.yml -f docker-compose.dev.yml"
                shift
                ;;
            --prod)
                env_file="docker-compose.yml -f docker-compose.prod.yml"
                shift
                ;;
            *)
                shift
                ;;
        esac
    done
    
    print_info "启动 MySQL MCP Server 服务..."
    
    if [ "$detach" = true ]; then
        docker-compose -f $env_file up -d
        print_success "服务已在后台启动"
        print_info "查看日志: $0 logs"
        print_info "停止服务: $0 down"
    else
        docker-compose -f $env_file up
    fi
}

# 停止服务
stop_services() {
    print_info "停止 MySQL MCP Server 服务..."
    docker-compose down
    print_success "服务已停止"
}

# 重启服务
restart_services() {
    print_info "重启 MySQL MCP Server 服务..."
    docker-compose restart
    print_success "服务已重启"
}

# 查看日志
show_logs() {
    local service=${1:-"mysql-mcp-server"}
    print_info "查看 $service 服务日志..."
    docker-compose logs -f "$service"
}

# 清理Docker资源
clean_docker() {
    print_warning "这将删除所有相关的Docker镜像、容器和数据卷"
    read -p "确定要继续吗？(y/N): " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        print_info "停止并删除容器..."
        docker-compose down -v --remove-orphans
        
        print_info "删除镜像..."
        docker rmi $(docker images "mysql-mcp-server*" -q) 2>/dev/null || true
        
        print_info "清理未使用的资源..."
        docker system prune -f
        
        print_success "Docker 资源清理完成"
    else
        print_info "取消清理操作"
    fi
}

# 测试MCP服务器连接
test_connection() {
    print_info "测试 MySQL MCP Server 连接..."
    
    # 检查容器是否运行
    if ! docker-compose ps | grep -q "mysql-mcp-server.*Up"; then
        print_error "MCP 服务器容器未运行，请先启动服务"
        return 1
    fi
    
    # 测试数据库连接
    print_info "测试数据库连接..."
    if docker-compose exec mysql mysql -u mcpuser -pmcppassword -e "SELECT 1;" testdb &>/dev/null; then
        print_success "数据库连接正常"
    else
        print_error "数据库连接失败"
        return 1
    fi
    
    # 测试MCP服务器
    print_info "测试 MCP 服务器..."
    if docker-compose exec mysql-mcp-server python -c "import src.mysql_mcp_server; print('MCP Server OK')" &>/dev/null; then
        print_success "MCP 服务器正常"
    else
        print_error "MCP 服务器测试失败"
        return 1
    fi
    
    print_success "所有测试通过"
}

# 主函数
main() {
    if [ $# -eq 0 ]; then
        show_help
        exit 0
    fi
    
    check_docker
    
    case $1 in
        build)
            shift
            build_image "$@"
            ;;
        up|start)
            shift
            start_services "$@"
            ;;
        down|stop)
            stop_services
            ;;
        restart)
            restart_services
            ;;
        logs)
            shift
            show_logs "$@"
            ;;
        clean)
            clean_docker
            ;;
        test)
            test_connection
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            print_error "未知命令: $1"
            show_help
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@"